﻿using System;
using System.Web;
using System.Web.Compilation;
using System.Web.Routing;

namespace K3R.Web.Routing {
	public class RoutingHandler : IVirtualRouteHandler {
		private string _virtualPath = "~/Default.aspx";

		public void SetVirtualPath(string virtualPath) {
			_virtualPath = virtualPath;
		}

		protected IHttpHandler CreatePage(string virtualPath) {
			var page = BuildManager.CreateInstanceFromVirtualPath(virtualPath, typeof(System.Web.UI.Page)) as IHttpHandler;

			if (page != null)
				return page;
			else throw new Exception("Virtual path was not recognised.");
		}

		protected IHttpHandler CreatePage() {
			return CreatePage(_virtualPath);
		}

		protected void AddRouteInformation(RequestContext requestContext, ref IHttpHandler page) {
			var routablePage = page as IRoutablePage;
			if (routablePage != null)
				routablePage.RequestContext = requestContext;
		}

		public virtual IHttpHandler GetHttpHandler(RequestContext requestContext) {
			if (requestContext == null)
				throw new Exception("Request Context cannot not be null");

			var page = CreatePage();
			AddRouteInformation(requestContext, ref page);
			return page;
		}
	}
}